package com.hotacorp.opencloud.userservice.service.impl;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.hotacorp.opencloud.common.commdata.Constants;
import com.hotacorp.opencloud.common.mybatisplus.PageData;
import com.hotacorp.opencloud.common.mybatisplus.Query;
import com.hotacorp.opencloud.userservice.dao.GatewayDefineDao;
import com.hotacorp.opencloud.userservice.entity.GatewayDefineEntity;
import com.hotacorp.opencloud.userservice.service.GatewayDefineService;

/**
 * 路由定义表接口实现
 * @author lwg
 *
 */
@Service("gatewayDefineService")
public class GatewayDefineServiceImpl extends ServiceImpl<GatewayDefineDao, GatewayDefineEntity> implements GatewayDefineService {
	@Autowired
	private StringRedisTemplate template;

    @Override
    public PageData queryPage(Map<String, Object> params) {
    	QueryWrapper<GatewayDefineEntity> query = new QueryWrapper<GatewayDefineEntity>();
    	if (StringUtils.isNotBlank((String)params.get("predicates"))) query.like("predicates", "%" + params.get("predicates") + "%");
        IPage<GatewayDefineEntity> page = this.page(
                new Query<GatewayDefineEntity>().getPage(params),
                query
        );

        return new PageData(page);
    }

	@Override
	public int synroute() {
		List<GatewayDefineEntity> list = baseMapper.selectList(new QueryWrapper<GatewayDefineEntity>().eq("status", 1));
		Set<String> dbids = list.stream().map(object->{
			return object.getId();
		}).collect(Collectors.toSet());
		Set<Object> rdids1 = template.boundHashOps(Constants.GATE_WAY).keys();
		Set<String> rdids = rdids1.stream().map(object->{
			return object.toString();
		}).collect(Collectors.toSet());
		Set<String> needstop = new HashSet<String>();
		needstop.addAll(rdids);
		needstop.removeAll(dbids);
		if (!needstop.isEmpty()) {
			template.boundHashOps(Constants.GATE_WAY).delete(needstop.toArray());
		}
		Set<String> needadd = new HashSet<String>();
		needadd.addAll(dbids);
		needadd.removeAll(rdids);
		list.stream().filter(new Predicate<GatewayDefineEntity>() {
		    @Override
		    public boolean test(GatewayDefineEntity person) {
		         return needadd.contains(person.getId());
		    }
		}).forEach(entity->{
			JSONObject object = new JSONObject();
			object.put("id", entity.getId());
			object.put("uri", entity.getUri());
			object.put("order", entity.getSeq());
			object.put("predicates", entity.getPredicates());
			object.put("filters", entity.getFilters());
			template.boundHashOps(Constants.GATE_WAY).put(entity.getId(), object.toString());
		});;
		return 1;
	}
	
    @Override
    public boolean save(GatewayDefineEntity entity) {
        boolean ret = retBool(baseMapper.insert(entity));
        if (ret && entity.getStatus() == 1) {
			JSONObject object = new JSONObject();
			object.put("id", entity.getId());
			object.put("uri", entity.getUri());
			object.put("order", entity.getSeq());
			object.put("predicates", entity.getPredicates());
			object.put("filters", entity.getFilters());
			template.boundHashOps(Constants.GATE_WAY).put(entity.getId(), object.toString());
        }
        return ret;
    }

    @Override
    public boolean updateById(GatewayDefineEntity entity) {
    	boolean ret = retBool(baseMapper.updateById(entity));
    	if (ret) {
            if (entity.getStatus() == 1) {
    			JSONObject object = new JSONObject();
    			object.put("id", entity.getId());
    			object.put("uri", entity.getUri());
    			object.put("order", entity.getSeq());
    			object.put("predicates", entity.getPredicates());
    			object.put("filters", entity.getFilters());
    			template.boundHashOps(Constants.GATE_WAY).put(entity.getId(), object.toString());
            } else {
            	template.boundHashOps(Constants.GATE_WAY).delete(entity.getId());
            }
    	}
        return ret;
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        if (CollectionUtils.isEmpty(idList)) {
            return false;
        }
        boolean ret = SqlHelper.retBool(baseMapper.deleteBatchIds(idList));
        if (ret) {
        	template.boundHashOps(Constants.GATE_WAY).delete(idList.toArray());
        }
        return ret;
    }

}